from infra.handler import BaseHandler
from .message_db import get_unread_message_counts
from .message_db import get_user_messages
from .message_db import update_message_status
import json
class MessageUnreadCountHandler(BaseHandler):
    """获取不同类型消息的未读数量"""
    async def get(self):
        try:
            user_id, _ = self.get_current_user()
            unread_counts = await get_unread_message_counts(user_id)
            self.write(json.dumps({"code":200,
                'data':unread_counts}))
        except Exception as e:
            print(e)
            self.write(json.dumps({"code":404,
                'msg':str(e),}))

class MessageListHandler(BaseHandler):
    """获取用户的所有消息，支持分页和消息类型过滤"""
    async def get(self):
        try:
            user_id, _ = self.get_current_user()
            page = int(self.get_argument("page", 1))
            page_size = int(self.get_argument("page_size", 20))
            # 获取消息类型参数
            message_type = self.get_argument("type", None)
            
            # 调用数据库函数获取消息列表
            message_list, total_count = await get_user_messages(
                user_id=user_id,
                page=page,
                page_size=page_size,
                message_type=message_type
            )
            
            self.write(json.dumps({
                "code": 200,
                "data": message_list,
                "total": total_count
            }))
        except Exception as e:
            print(e)
            self.write(json.dumps({
                "code": 404,
                "msg": str(e)
            }))
    async def post(self):
        """更新消息状态为已读"""
        try:
            user_id, _ = self.get_current_user()
            body = json.loads(self.request.body)
            message_ids = body.get('message_ids', [])
           
            
            if not message_ids:
                self.write(json.dumps({
                    "code": 400,
                    "msg": "消息ID列表不能为空"
                }))
                return
            
            success = await update_message_status(message_ids)
            if success:
                self.write(json.dumps({
                    "code": 200,
                    "msg": "消息状态更新成功"
                }))
            else:
                self.write(json.dumps({
                    "code": 400,
                    "msg": "消息状态更新失败"
                }))
        except Exception as e:
            print(e)
            self.write(json.dumps({
                "code": 404,
                "msg": str(e)
            }))